// 商品分类
import api from '@/tools/api.js'
import promise from '@/tools/promise'
import { SUCCESS_STATUS } from '@/config/status'
import {
  GOODS_CLASS_ATTR_ALL,
  GOODS_PARENT_CLASS_ATTR,
  GOODS_ATTR_LIST,
  GOODS_ATTR_INFO
} from '@/store/mutation-types'

const state = {
  pageData: {
    total: 1,
    per_page: 15,
    current_page: 1,
    last_page: 1
  },
  goodsClassAttrAll: [],
  goodsParentClassAttr: [],
  goodsAttr: [],
  goodsAttrInfo: {}
}

// mutations
const mutations = {
  [GOODS_CLASS_ATTR_ALL] (state, res) {
    state.goodsClassAttrAll = res
  },
  [GOODS_PARENT_CLASS_ATTR] (state, res) {
    state.goodsParentClassAttr = res
  },
  [GOODS_ATTR_LIST] (state, res) {
    state.goodsAttr = res.data
    state.pageData.total = Number(res.total)
    state.pageData.per_page = Number(res.per_page)
    state.pageData.current_page = Number(res.current_page)
    state.pageData.last_page = Number(res.last_page)
  },
  [GOODS_ATTR_INFO] (state, res) {
    state.goodsAttrInfo = res
  }
}

// actions
const actions = {
  // 获取全部商品分类属性
  async goodsClassAttrAll ({ commit }, payload) {
    let allRes = await api('servergoods/goods/GoodsCategoryAttrs/attrsAllList', payload)
    if (SUCCESS_STATUS === allRes.status) {
      commit(GOODS_CLASS_ATTR_ALL, allRes.res)
    }
  },
  // 获取父级商品分类属性
  async goodsParentClassAttr ({ commit }, payload) {
    let attrRes = await api('servergoods/goods/GoodsCategory/parentAllAttrs', payload)
    if (SUCCESS_STATUS === attrRes.status) {
      commit(GOODS_PARENT_CLASS_ATTR, attrRes.res)
    }
  },
  // 获取商品属性列表
  async goodsAttr ({ commit }, payload) {
    let attrRes = await api('servergoods/goods/GoodsCategoryAttrs/attrsList', payload)
    commit(GOODS_ATTR_LIST, attrRes.res)
  },
  // 添加商品属性
  async goodsAttrAdd ({ commit }, payload) {
    let addRes = await api('servergoods/goods/GoodsCategoryAttrs/addAttr', payload)
    return promise(addRes)
  },
  // 删除商品属性
  async goodsAttrDel ({ commit }, payload) {
    let delRes = await api('servergoods/goods/GoodsCategoryAttrs/delAttrs', payload)
    return promise(delRes)
  },
  // 获取商品属性详情
  async goodsAttrInfo ({ commit }, payload) {
    let infoRes = await api('servergoods/goods/GoodsCategoryAttrs/oneAttrInfo', payload)
    commit(GOODS_ATTR_INFO, infoRes.res)
  },
  // 编辑商品属性
  async goodsAttrEdit ({ commit }, payload) {
    let editRes = await api('servergoods/goods/GoodsCategoryAttrs/editAttr', payload)
    return promise(editRes)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
